# encoding=utf-8
import datetime
import os
import traceback

from seg_system import ApplicationConfig
from nb_log import get_logger


class ConsoleService:
    DEBUG = 1
    INFO = 2
    WARNING = 3
    ERROR = 4
    CRITICAL = 5

    console_logger = get_logger(name='ConsoleLog', is_add_stream_handler=True,
                                log_path=os.path.join(ApplicationConfig.PathConfig.SYSTEM_RESOURCE, ApplicationConfig.PathConfig.SYSTEM_LOG_FOLDER),
                                log_filename=ApplicationConfig.PathConfig.SYSTEM_LOG_FILE)

    @staticmethod
    def try_log(f, m: str):
        try:
            f(m)
        except Exception as e:
            print(traceback.format_exc())

    @staticmethod
    def console_log(message: str, level: int = DEBUG):
        if level == ConsoleService.DEBUG:
            # ConsoleService.console_logger.debug(message)
            ConsoleService.try_log(ConsoleService.console_logger.debug, message)
        elif level == ConsoleService.INFO:
            ConsoleService.try_log(ConsoleService.console_logger.info, message)
            # ConsoleService.console_logger.info(message)
        elif level == ConsoleService.WARNING:
            ConsoleService.try_log(ConsoleService.console_logger.warning, message)
            # ConsoleService.console_logger.warning(message)
        elif level == ConsoleService.ERROR:
            ConsoleService.try_log(ConsoleService.console_logger.error, message)
            # ConsoleService.console_logger.error(message)
        else:
            # ConsoleService.console_logger.critical(message)
            ConsoleService.try_log(ConsoleService.console_logger.critical, message)

    @staticmethod
    def get_logger():
        return ConsoleService.console_logger

    @staticmethod
    def make_logger():
        file_name = "Consolelog{}.txt".format(datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S"))
        ConsoleService.console_logger = \
            get_logger(name='ConsoleLog', is_add_stream_handler=True,
                       log_path=os.path.join(ApplicationConfig.PathConfig.SYSTEM_RESOURCE,
                                             ApplicationConfig.PathConfig.SYSTEM_LOG_FOLDER),
                       log_filename=file_name)
        ConsoleService.console_logger.info('logger update !!, name is: {}'.format(file_name))